package com.huqu.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import vn.hus.nlp.tokenizer.VietTokenizer;

public class ApplicationHelper {
	public static VietTokenizer vietTokenizer = new VietTokenizer();
	private static ApplicationContext context = new ClassPathXmlApplicationContext(
			"SpringHqContext.xml");
	
	public static void test(){
		try {
			String keysearch="www.zing.vn @ ? >< học sinh học môn sinh học";
			String[] tokens = vietTokenizer.tokenize(keysearch);
			System.out.println("tokens.lenght()= "+tokens.length);
			if (tokens != null && tokens.length > 0)
				System.out.println(tokens[0]);
			else {
				System.out.println("------no token  found");
			}
		} catch (Exception e) {
			System.out.println("---------------------Chán----------------------");
		}
	}

	public static Object findBean(String reposityName) {

		return context.getBean(reposityName);
	}

	/* redirect page */
	public static void redirectTo(String url) {
		try {
			ExternalContext context = FacesContext.getCurrentInstance()
					.getExternalContext();
			context.redirect("pages/navigate/" + url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/* redirect page */
	public static void gotoPage(String namepage) {
		try {
			ExternalContext context = FacesContext.getCurrentInstance()
					.getExternalContext();
			context.redirect(namepage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String convertToMD5(String arg) {
		String hashed_key = "";

		try {
			byte[] intext = arg.getBytes();
			StringBuffer sb = new StringBuffer();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] md5rslt = md5.digest(intext);
			for (int i = 0; i < md5rslt.length; i++) {
				sb.append(String.format("%02x", 0xff & md5rslt[i]));
			}
			hashed_key = sb.toString();
		} catch (Exception e2) {
			System.out.println(e2);
		}
		return hashed_key;
	}

	// get parameter tu url
	public static Map<String, String> getParameter() {
		return FacesContext.getCurrentInstance().getExternalContext()
				.getRequestParameterMap();
	}

	// load ngon ngu theo URL
	public static void loadLanguage() {
		try {
			if (getParameter().get("para1") != null) {
				if (getParameter().get("para1").toUpperCase().equals("EN")) {
					FacesContext.getCurrentInstance().getViewRoot()
							.setLocale(Locale.US);
				} else {
					Locale locale = new Locale("vi", "VN");
					FacesContext.getCurrentInstance().getViewRoot()
							.setLocale(locale);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * get ExternalContext
	 */
	public static ExternalContext getExContext() {
		return getContext().getExternalContext();
	}

	public static HttpServletResponse getResponse() {
		return (HttpServletResponse) getExContext().getResponse();
	}

	public static FacesContext getContext() {
		return FacesContext.getCurrentInstance();
	}

	/*
	 * getRequest Page
	 */
	public static HttpServletRequest getRequest() {
		return (HttpServletRequest) getExContext().getRequest();
	}

	public static void showMessageSuccess(String mes) {
		getContext().addMessage(null,
				new FacesMessage(ApplicationConstant.SEVERITY_INFO, mes, null));
	}

	public static void showMessageErro(String mes) {
		getContext()
				.addMessage(
						null,
						new FacesMessage(ApplicationConstant.SEVERITY_ERROR,
								mes, null));
	}

	/* upload file */
	public static int copyFileImage(String fileName, InputStream in) {
		try {
			String destination="src\\main\\webapp\\images\\upload\\baiviet\\";
			// write the inputStream to a FileOutputStream
			OutputStream out = new FileOutputStream(new File(destination+ fileName));

			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = in.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}

			in.close();
			out.flush();
			out.close();

			System.out.println("New file created= "+fileName);
			return 1;
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	/* upload file */
	public static int copyFileImage1(String fileName, InputStream in, String address) {
		try {
			String destination=address;
			// write the inputStream to a FileOutputStream
			OutputStream out = new FileOutputStream(new File(destination+ fileName));

			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = in.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}

			in.close();
			out.flush();
			out.close();

			System.out.println("New file created= "+fileName);
			return 1;
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	//kiểm tra ngày (kiểm tra xem ngày cần kiểm tra có trước 3 ngày trước ko)
	// vd: hiện tại: 2014-11-22 00:57:29 ngày kiểm tra= 2014-11-19 00:57:29 thì kết quả là đúng
	public static boolean isDayAgo2(Date date, int numDay){
		try {
			Calendar cal = Calendar.getInstance();
			cal.setTime(new Date());
			System.out.println("cal.getTimeInMillis()= "+cal.getTimeInMillis());
			cal.add(Calendar.DAY_OF_MONTH, numDay*(-1));
			System.out.println("cal.getTimeInMillis()= "+cal.getTimeInMillis());
			
			Calendar cal2=Calendar.getInstance();
			cal.setTime(date);
			
			System.out.println("cal2.getTimeInMillis()= "+cal2.getTimeInMillis());
			if(cal2.getTimeInMillis()>=cal.getTimeInMillis()){
				return true;
			}else return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static boolean isDayAgo(Date date, int numDay){
		try {
			Date curDate= new Date();
			long dayAgo=date.getTime()-numDay*24*60*60*1000;
			long day=date.getTime();
			if(day<=dayAgo){
				return true;
			}else return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static void setSession(String name, Object object) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();

		HttpSession httpSession = request.getSession(false);
		httpSession.setAttribute(name, object);
	}

	public static Object getSession(String name) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		HttpSession httpSession = request.getSession(false);
		Object reqdObj = (Object) httpSession.getAttribute(name);
		return reqdObj;
	}
}
